package com.saret.utils;


import java.io.File;
import java.net.URL;

/**
 * User: biniam.gebremichael
 * Date: 2/3/11
 */
public class FileLocator {

    static String installationDir = System.getProperty("HOME");


    public static File getRootDir() {
        return new File(getFilePath(FileLocator.class.getName()));
    }

    public static File getConfigDir() {
        return new File(getInstallationDir(), "config");
    }

    public static File getWorkingDir() {
        return chainDirs(getInstallationDir(), "temp");
    }

    public static File getInstallationDir() {
        File file = installationDir != null ? new File(installationDir) : getRootDir();
        while (!file.getName().endsWith("classes")) {
            file = file.getParentFile();
        }
        return file.getParentFile();
    }

    public static File getDownloadDir() {
        return chainDirs(getWorkingDir(), "download");
    }

    public static File getCompletedDir() {
        return chainDirs(getWorkingDir(), "completed");
    }

    public static File getTranslateDir() {
        return chainDirs(getConfigDir(), "translate");
    }

    public static File getConvertedDir() {
        return chainDirs(getWorkingDir(), "converted");
    }

    public static File getConfigFile(String... path) {
        return chainDirs(getConfigDir(), path);
    }

    public static File chainDirs(File parent, String... dirs) {
        File result = parent;
        for (String s : dirs) {
            result = new File(result, s);
        }
        result.mkdirs();
        return result;
    }


    public static String getFilePath(String className) {
        if (!className.startsWith("/")) {
            className = "/" + className;
        }
        className = className.replace('.', '/');
        className = className + ".class";
        URL classUrl = new FileLocator().getClass().getResource(className);
        if (classUrl != null) {
            String temp = classUrl.getFile();
            if (temp.startsWith("file:")) {
                return temp.substring(5);
            }
            return temp;
        } else {
            return "\nClass '" + className +
                    "' not found in \n'" +
                    System.getProperty("java.class.path") + "'";
        }
    }


}
